<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// 
//  pm_model.php
//  phpweb
//  
//  Created by WillLee on 2011-07-14.
//  Copyright 2011 lishuzu. All rights reserved.
// 



class Pm_model extends CI_Model
{
		function __construct(){
			parent::__construct();
			$this->load->model('user_model');
			$this->user = $this->session->userdata('user') ? $this->session->userdata('user') : '';
			$this->uid = $this->user ? $this->user['uid'] : '';
		}
		
		// A->B 第一条短消息，写入三条， 
		// related= 0 是两人的第一条，每次发消息的时候，更新标题和内容和时间，还有是否已经读取状态。显示在列表里，直接看到消息。
		// related= 1 的，是消息正文，进入后，倒序排列
		// 
		// msgfromid b , msgtoid A 的是 A　看到的自己发给对方的内容
		// 
		// 短消息的列表又根据时间来过滤长度。
		// msgfrom 空 msgfromid, msgtoid 都为 0 为公共消息
		// msgfrom 空 msgfromid = 0 ,msgtoid 不为0 为系统消息
		// 
		// msgfromid与msgtoid相等, folder = outbox为草稿箱
		//  delstatus 0 都没有删除 ,1 msgfromid 主动删除 2 msgtoid 删除为2
		
		function get_pm_by_pmid($uid, $pmid) {
			
			$query = $this->db->query("SELECT * FROM ".$this->db->dbprefix('pms')." WHERE pmid='$pmid' AND (msgtoid IN ('$uid','0') OR msgfromid='$uid')");
			return $query->result_array();
		}

		//得到发件人和收件人的所有短信
		function get_pm_by_touid($uid, $touid, $offset= '0', $ppp = "20") {
			$wheresql = "(msgfromid='$uid' AND msgtoid='$touid'  AND related>'0' AND delstatus IN (0,2)) OR (msgfromid='$touid' AND msgtoid='$uid' AND related>'0' AND delstatus IN (0,1)) ORDER BY dateline DESC";
			$sql = "SELECT * FROM ".$this->db->dbprefix('pms')." WHERE (msgfromid='$uid' AND msgtoid='$touid'  AND related>'0' AND delstatus IN (0,2)) OR (msgfromid='$touid' AND msgtoid='$uid' AND related>'0' AND delstatus IN (0,1)) ORDER BY dateline DESC";

			$data['count'] = $this->db->query("SELECT count(*) as num FROM ".$this->db->dbprefix('pms')." WHERE  $wheresql")->first_row()->num;
			
			if ($data['count']) {
				$query = $this->db->query("SELECT * FROM ".$this->db->dbprefix('pms')." WHERE $wheresql LIMIT $offset, $ppp");
				
				$data['list'] = $query->result_array();
				if ($data['list']) {
					uasort($data['list'], 'pm_datelinesort');
				}
			}

			return $data;
		}

		// 得到单条信息
		function get_pmnode_by_pmid($uid, $pmid, $type = 0) {
			$arr = array();
			if($type == 1) {
				$query = $this->db->query("SELECT * FROM ".$this->db->dbprefix('pms')." WHERE msgfromid='$uid' and folder='inbox' ORDER BY dateline DESC LIMIT 1");
				$arr = $query->row_array();
			} elseif($type == 2) {
				$query = $this->db->fetch_first("SELECT * FROM ".$this->db->dbprefix('pms')." WHERE msgtoid='$uid' and folder='inbox' ORDER BY dateline DESC LIMIT 1");
				$arr = $query->row_array();
			} else {
				$query = $this->db->fetch_first("SELECT * FROM ".$this->db->dbprefix('pms')." WHERE pmid='$pmid'");
				$arr = $query->row_array();
			}
			return $arr;
		}
		
		
		//发送短消息  msgfrom 是用户资料 msgto 是uid
		function sendpm($subject = '', $message, $msgfrom, $msgto, $pmid = 0, $savebox = 0, $related = 0) {


			if($savebox && $pmid) {
				//更改信息到发件箱
				$setarr = array(
					'msgtoid' => $msgto,
					'subject' => $subject,
					'message' => $message,
					'dateline' => now(),
					'related' => $related,
					);
				$where = array(
						'pmid' => $pmid,
						'msgfromid' => $$msgfrom,
						'folder' => 'outbox',
						'related' => '0'
					);
				$this->db->where($where);
				$this->db->update('pms', $setarr);
			} else {
				$box = $savebox ? 'outbox' : 'inbox';

				$subject = trim($subject);
				if($subject == '' && !$related) {
					$subject = cutstr(trim($message), 75);
				} else {
					$subject = cutstr(trim($subject), 75, ' ');
				}
				// 有发送人 发送
				if($msgfrom['uid']) {
					if($msgto) {
						$where = array(
								'msgfromid' => $msgfrom['uid'],
								'msgtoid' => $msgto,
								'folder' => 'inbox',
								'related' => '0'
							);
						$this->db->where($where);
						$sessionexist = $this->db->count_all_results('pms');
					} else {
						$sessionexist = 0;
					}

					// 是否已经有对话存在 没有 或者 多余都重置为一条
					if(!$sessionexist || $sessionexist > 1) {
						if($sessionexist > 1) {
							$where = array(
									'msgfromid' => $msgfrom['uid'],
									'msgtoid' => $msgto,
									'folder' => 'inbox',
									'related' => '0'
								);
							$this->db->where($where);
							$this->db->delete('pms');
						}
						$setarr = array(
							'msgfrom' => $msgfrom['username'],
							'msgfromid' => $msgfrom['uid'],
							'msgtoid' => $msgto,
							'folder' => $box,
							'new' => '1',
							'subject' => $subject,
							'dateline' => now(),
							'related' => '0',
							'message' => $message
							);
						$this->db->insert('pms', $setarr);
						$lastpmid = $this->db->insert_id();
					} else {
						$setarr = array(
							'subject' => $subject,
							'message' => $message,
							'dateline' => now(),
							'new' => '1',
							);
						$where = array(
								'msgfromid' => $msgfrom['uid'],
								'msgtoid' => $msgto,
								'folder' => 'inbox',
								'related' => '0'
							);
						$this->db->where($where);
						$this->db->update('pms', $setarr);
					}
					// 直接发送
					if($msgto && !$savebox) {

						$where = array(
								'msgfromid' => $msgto,
								'msgtoid' => $msgfrom['uid'],
								'folder' => 'inbox',
								'related' => '0'
							);
						$this->db->where($where);
						$sessionexist = $this->db->count_all_results('pms');

						if($msgfrom['uid'] && !$sessionexist) {

							$setarr = array(
								'msgfrom' => $msgfrom['username'],
								'msgfromid' => $msgto,
								'msgtoid' => $msgfrom['uid'],
								'folder' => $box,
								'new' => '0',
								'subject' => $subject,
								'dateline' => now(),
								'related' => '0',
								'message' => $message
								);
							$this->db->insert('pms', $setarr);
							$lastpmid = $this->db->insert_id();
						}
						$setarr = array(
							'msgfrom' => $msgfrom['username'],
							'msgfromid' => $msgfrom['uid'],
							'msgtoid' => $msgto,
							'folder' => $box,
							'new' => '1',
							'subject' => $subject,
							'dateline' => now(),
							'related' => '1',
							'message' => $message
							);
						$this->db->insert('pms', $setarr);
						$lastpmid = $this->db->insert_id();
					}
					if($msgto) {
						$this->db->query("REPLACE INTO ".$this->db->dbprefix."newpm (uid) VALUES ('$msgto')");	
					}
				// 系统消息
				} else {
					$setarr = array(
						'msgfrom' => $msgfrom['username'],
						'msgfromid' => $msgfrom['uid'],
						'msgtoid' => $msgto,
						'folder' => $box,
						'new' => '1',
						'subject' => $subject,
						'dateline' => now(),
						'related' => '0',
						'message' => $message
						);
					$this->db->insert('pms', $setarr);
					$lastpmid = $this->db->insert_id();
				}
			}
			return $lastpmid;
		}
		
		
		// 忽略未读邮件
		function set_ignore($uid) {
			$this->db->query("DELETE FROM ".$this->db->dbprefix('newpm')." WHERE uid='$uid'");
		}
		
		
		// bool/array uc_pm_checknew(integer uid [, bool more])
		// 函数参数
		// 参数 	含义
		// integer uid 	用户 ID
		// bool more 	是否显示更多信息
		// 2:返回短消息数、公共消息数、最后消息时间, 最后消息内容
		// 1:返回短消息数、公共消息数、最后消息时间
		// 0:(默认值) 只返回短消息数
		
		// 检查新邮件
		function check_newpm($uid, $more = '0') {
			// 1:返回短消息数、公共消息数、最后消息时间
			// 0:(默认值) 只返回短消息数
			if($more < 2) {
				$newpm = $this->db->query("SELECT count(*) as num FROM ".$this->db->dbprefix('newpm')." WHERE uid='".$uid."'")->first_row()->num;

				if($newpm) {
					$newpm = $this->db->query("SELECT count(*) as num FROM ".$this->db->dbprefix('pms')." WHERE (related='1' AND msgfromid>'0' OR msgfromid='0') AND msgtoid='$uid' AND folder='inbox' AND new='1'")->first_row()->num;
					if($more) {
						$newprvpm = $this->db->query("SELECT count(*) as num FROM ".$this->db->dbprefix('pms')." WHERE related='0' AND msgfromid>'0' AND msgtoid='$uid' AND folder='inbox' AND new='1'")->first_row()->num;
						return array('newpm' => $newpm, 'newprivatepm' => $newprvpm);
					} else {
						return $newpm;
					}
				}
				return '0';
			}
			return '0';
		}
		
		
		
		// 得到短消息列表
		function get_pm_list($uid, $pmnum, $folder, $filter, $start = '0', $ppp = 20) {
			$ppp = $ppp ? $ppp : 10;
			switch($folder) {
				case 'newbox':
					$folder = 'inbox';
					$filter = 'newpm';
				case 'outbox':
				case 'inbox':
					if($filter == 'newpm') {
						$filteradd = "pm.msgtoid='$uid' AND (pm.related='0' AND pm.msgfromid>'0' OR pm.msgfromid='0') AND pm.folder='inbox' AND pm.new='1'";
					} elseif($filter == 'systempm') {
						$filteradd = "pm.msgtoid='$uid' AND pm.msgfromid='0' AND pm.folder='inbox'";
					} elseif($filter == 'privatepm') {
						//直接得到系统消息
//  						$filteradd = "pm.msgtoid='$uid' AND pm.related='0' AND pm.msgfromid>'0' AND pm.folder='inbox'";
 						$filteradd = "pm.msgtoid IN ('0', '$uid') AND pm.related='0' AND pm.msgfromid>='0' AND pm.folder='inbox'";
					} elseif($filter == 'announcepm') {
						$filteradd = "pm.msgtoid='0' AND pm.folder='inbox'";
					} else {
						$filteradd = "pm.msgtoid='$uid' AND pm.related='0' AND pm.folder='inbox'";
					}
					$sql = "SELECT pm.*,u.name as msgfrom FROM ".$this->db->dbprefix('pms')." pm
						LEFT JOIN ".$this->db->dbprefix('user')." u ON pm.msgfromid = u.uid
						WHERE $filteradd ORDER BY pm.dateline DESC LIMIT $start, $ppp";
					$countsql = "SELECT count(*) as num FROM ".$this->db->dbprefix('pms')." pm
						WHERE $filteradd ORDER BY pm.dateline DESC";
					break;
				case 'searchbox':
					$filteradd = "msgtoid='$uid' AND folder='inbox' AND message LIKE '%".(str_replace('_', '\_', addcslashes($filter, '%_')))."%'";
					$sql = "SELECT * FROM ".$this->db->dbprefix('pms')."
						WHERE $filteradd ORDER BY dateline DESC LIMIT $start, $ppp";
					break;
				case 'savebox':
					break;
			}
			$query = $this->db->query($sql);
			//查询总数 用来分页
			$totalnum = $this->db->query($countsql)->first_row()->num;
			$array = array();
			$today = now() - now() % 86400;
			foreach($query->result_array() as $data) {
				$daterange = 5;
				if($data['dateline'] >= $today) {
					$daterange = 1;
				} elseif($data['dateline'] >= $today - 86400) {
					$daterange = 2;
				} elseif($data['dateline'] >= $today - 172800) {
					$daterange = 3;
				} elseif($data['dateline'] >= $today - 604800) {
					$daterange = 4;
				}
				$data['daterange'] = $daterange;
				$data['subject'] = htmlspecialchars($data['subject']);
				if($filter == 'announcepm') {
					// unset($data['msgfromid'], $data['msgfrom']);
				}
				$data['touid'] = $uid == $data['msgfromid'] ? $data['msgtoid'] : $data['msgfromid'];
				$array['list'][] = $data;
			}
			if($folder == 'inbox') {
				$this->db->query("DELETE FROM ".$this->db->dbprefix('newpm')." WHERE uid='$uid'");
			}
			$array['count'] = $totalnum;
			return $array;
		}
		
		function get_pagepm_list($uid){
			if ($uid) {
				//page
				$_SGLOBAL = $this->config->item('SGLOBAL');
				$_SGLOBAL['multipage_config']['base_url'] = base_url().'pm/index/';
				$_SGLOBAL['multipage_config']['uri_segment'] = '3';
				$_SGLOBAL['multipage_config']['per_page'] = '20';
				$offset = $this->uri->segment($_SGLOBAL['multipage_config']['uri_segment']);
				$pmdata = $this->get_pm_list($uid, 10, 'inbox', 'privatepm', '0', $_SGLOBAL['multipage_config']['per_page']);
				if ($pmdata) {
					foreach ($pmdata['list'] as $key=>$value) {
						$value['avatar_small'] = avatar($value['touid'], 'small');
						realname_set($value['msgfromid'], $value['msgfrom']);
						$pmdata['list'][$key] = $value;
					}
					//page
					$_SGLOBAL['multipage_config']['total_rows'] = $pmdata['count'];//debug
					$this->pagination->initialize($_SGLOBAL['multipage_config']);
					$multi = $this->pagination->create_links();
					$data['multi'] = $multi;
					$data['list'] = $pmdata['list'];
					return $data;
				}else{
					return array();
				}
			}
			return false;
		}
		
		
		// 发件人和收件人所有信息 分页
		function get_pagepmview_list($uid, $pmid, $touid){
			$uid = intval($uid);
			$touid = intval($touid);
			$pmid = @is_numeric($pmid) ? $pmid : 0;
			
			if ($uid && $touid) {
				$mpurl = base_url()."pm/read/index/?pmid=$pmid&touid=$touid";
				//每页查看数
				$perpage = empty($_GET['perpage'])?0:intval($_GET['perpage']);
				if(!in_array($perpage, array(20,50,100))) $perpage = 50;
				$perpages = array($perpage => ' selected');
				//分页
				$multipage_config = $this->config->item('multipage_config', 'SGLOBAL');
				$multipage_config['base_url'] = $mpurl;
				$multipage_config['page_query_string'] = TRUE;
				$multipage_config['uri_segment'] = '4';
				$offset = $this->input->get('per_page') ? $this->input->get('per_page', true) : 0;
				$pms = $this->pm_view($uid, $pmid, $touid, $offset, $perpage);
				if (!empty($pms['list'])) {
					foreach ($pms['list'] as $key => $value) {
						realname_set($value['msgfromid'], $value['msgfrom']);
						$value['avatar_small'] = avatar($value['msgfromid'], 'small');
						$pms['list'][$key] = $value;
					}
					realname_get();
				
					$multipage_config['per_page'] = $perpage;
					$multipage_config['total_rows'] = $pms['count'];
					$this->pagination->initialize($multipage_config);
					$multi = $this->pagination->create_links();
					$data['list'] = $pms['list'];
					$data['multi'] = $multi;
					return $data;
				}else{
					return array();
				}

			}
			return false;
		}
		
		// 得到发件人和收件人所有短信
		function pm_view($uid, $pmid, $touid = 0, $offset = 0, $perpage= '20') {
			$uid = intval($uid);
			$touid = intval($touid);
			$pmid = @is_numeric($pmid) ? $pmid : 0;

	 		if(empty($pmid)) {
		 		$pms = $this->get_pm_by_touid($uid, $touid, $offset, $perpage);
		 	} else {
		 		$pms = $this->get_pm_by_pmid($uid, $pmid);
		 	}
			$status = FALSE;
			if (!empty($pms['list'])) {
				foreach($pms['list'] as $key => $pm) {
					!$status && $status = $pm['msgtoid'] && $pm['new'];
				}
			}else{
				!$status && $status = $pms[0]['msgtoid'] && $pms[0]['new'];
			}

			$status && $this->set_pm_status($uid, $touid, $pmid);
			return $pms;
		}
		
		// 设置消息状态
		function set_pm_status($uid, $touid, $pmid = 0, $status = 0) {
			if(!$status) {
				$oldstatus = 1;
				$newstatus = 0;
			} else {
				$oldstatus = 0;
				$newstatus = 1;
			}
			if($touid) {
				$ids = is_array($touid) ? implode($touid) : $touid;
				$this->db->query("UPDATE ".$this->db->dbprefix('pms')." SET new='$newstatus' WHERE msgfromid IN ($ids) AND msgtoid='$uid' AND new='$oldstatus'", 'UNBUFFERED');
			}
			if($pmid) {
				$ids = is_array($pmid) ? implode($pmid) : $pmid;
				$this->db->query("UPDATE ".$this->db->dbprefix('pms')." SET new='$newstatus' WHERE pmid IN ($ids) AND msgtoid='$uid' AND new='$oldstatus'", 'UNBUFFERED');
			}
		}
		
		
		// 删除短消息
		// 参数 	含义
		// integer uid 	用户 ID
		// string folder 	短消息所在的文件夹
		// inbox:收件箱
		// outbox:发件箱
		// array pmids 	消息 ID 数组
		// 返回值
		// 值 	含义
		// integer 	被删除的短消息数
		function deletepm($uid, $pmids) {
			$this->db->where('msgtoid', $uid);
			$this->db->where_in('pmid', $pmids);
			$this->db->delete('pms');
			$delnum = $this->db->affected_rows();
			return $delnum;
		}

		//本接口函数将删除和 uid 对话的 touids 中的所有短消息。 
		// 参数 	含义
		// integer uid 	用户 ID
		// array touids 	对方用户 ID 数组
		// 返回值
		// 值 	含义
		// integer 	被删除的短消息数
		// 删除的每一条短消息  会进行对方删除状态的检测，如果短消息对方也是删除状态，那么当前消息将在数据库中删除，否则只记录一个删除标记。 
		//  delstatus 0 都没有删除 ,1 msgfromid 主动删除 2 msgtoid 删除为2
		function deleteuidpm($uid, $ids, $folder = 'inbox', $filter = '') {
			$delnum = 0;
			if($folder == 'inbox' || $folder == 'newbox') {
				if($filter == 'announcepm') {
					$pmsadd = "pmid IN (".implode($ids).")";
					$this->db->query("DELETE FROM ".$this->db->dbprefix('pms')." WHERE folder='inbox' AND msgtoid='0' AND $pmsadd", 'UNBUFFERED');
				} elseif($ids){
					$delnum = 1;
					$deluids = implode($ids);
					$this->db->query("DELETE FROM ".$this->db->dbprefix('pms')."
						WHERE msgfromid IN ($deluids) AND msgtoid='$uid' AND folder='inbox' AND related='0'", 'UNBUFFERED');
					$this->db->query("UPDATE ".$this->db->dbprefix('pms')." SET delstatus=2
						WHERE msgfromid IN ($deluids) AND msgtoid='$uid' AND folder='inbox' AND delstatus=0", 'UNBUFFERED');
					$this->db->query("UPDATE ".$this->db->dbprefix('pms')." SET delstatus=1
						WHERE msgtoid IN ($deluids) AND msgfromid='$uid' AND folder='inbox' AND delstatus=0", 'UNBUFFERED');
					$this->db->query("DELETE FROM ".$this->db->dbprefix('pms')."
						WHERE msgfromid IN ($deluids) AND msgtoid='$uid' AND delstatus=1 AND folder='inbox'", 'UNBUFFERED');
					$this->db->query("DELETE FROM ".$this->db->dbprefix('pms')."
						WHERE msgtoid IN ($deluids) AND msgfromid='$uid' AND delstatus=2 AND folder='inbox'", 'UNBUFFERED');
				}
			}elseif($folder == 'savebox') {
					$this->db->query("DELETE FROM ".$this->db->dbprefix('pms')."
						WHERE pmid IN (".implode($ids).") AND folder='outbox' AND msgfromid='$uid'", 'UNBUFFERED');
					$delnum = 1;
			}
			return $delnum;
		}
		
}
?>